const express = require('express');
const router = express.Router();
const mysql = require('mysql2');
const { db } = require('../config');
const pool = mysql.createPool(db);

// 获取订单列表（带商品信息）
router.get('/', (req, res) => {
  const user_id = req.query.user_id;
  if (!user_id) {
    return res.status(400).json({ code: 1, message: '缺少用户ID' });
  }
  pool.query(
    'SELECT * FROM `order` WHERE user_id = ? ORDER BY create_time DESC',
    [user_id],
    (err, orders) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, data: orders });
    }
  );
});

// 管理员获取所有订单列表
router.get('/admin', (req, res) => {
  pool.query(
    `SELECT o.*, u.username FROM \`order\` o 
     LEFT JOIN user u ON o.user_id = u.id 
     ORDER BY o.create_time DESC`,
    (err, orders) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, data: orders });
    }
  );
});

// 获取当日订单统计
router.get('/stats/today', (req, res) => {
  const today = new Date().toISOString().split('T')[0]; // 获取今天的日期 YYYY-MM-DD
  pool.query(
    `SELECT 
       COUNT(*) as total_orders,
       SUM(total_price) as total_amount,
       COUNT(CASE WHEN status = '已支付' THEN 1 END) as paid_orders,
       COUNT(CASE WHEN status = '已完成' THEN 1 END) as completed_orders
     FROM \`order\` 
     WHERE DATE(create_time) = ?`,
    [today],
    (err, results) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      const stats = results[0];
      res.json({ 
        code: 0, 
        data: {
          total_orders: stats.total_orders || 0,
          total_amount: parseFloat(stats.total_amount || 0).toFixed(2),
          paid_orders: stats.paid_orders || 0,
          completed_orders: stats.completed_orders || 0
        }
      });
    }
  );
});

// 模拟结算：生成订单、订单商品并清空购物车
router.post('/', (req, res) => {
  const { user_id } = req.body;
  console.log('收到结算请求', user_id);
  if (!user_id) {
    console.log('缺少用户ID');
    return res.status(400).json({ code: 1, message: '缺少用户ID' });
  }
  // 查询购物车商品
  pool.query(
    'SELECT cart.goods_id, cart.quantity, goods.price FROM cart JOIN goods ON cart.goods_id = goods.id WHERE cart.user_id = ?',
    [user_id],
    (err, cartItems) => {
      console.log('查询购物车商品', err, cartItems);
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      if (cartItems.length === 0) return res.json({ code: 1, message: '购物车为空' });
      // 计算总价
      let total = 0;
      cartItems.forEach(item => {
        total += item.price * item.quantity;
      });
      // 新建订单
      pool.query(
        'INSERT INTO `order` (user_id, total_price, status, create_time) VALUES (?, ?, ?, NOW())',
        [user_id, total, '待支付'],
        (err2, result) => {
          console.log('插入订单', err2, result);
          if (err2) return res.status(500).json({ code: 1, message: '数据库错误' });
          const orderId = result.insertId;
          // 插入订单商品
          const orderGoodsValues = cartItems.map(item => [orderId, item.goods_id, item.quantity]);
          pool.query(
            'INSERT INTO order_goods (order_id, goods_id, quantity) VALUES ?',
            [orderGoodsValues],
            (err3, result3) => {
              console.log('插入订单商品', err3, result3);
              if (err3) return res.status(500).json({ code: 1, message: '数据库错误' });
              // 清空购物车
              pool.query(
                'DELETE FROM cart WHERE user_id = ?',
                [user_id],
                (err4, result4) => {
                  console.log('清空购物车', err4, result4);
                  if (err4) return res.status(500).json({ code: 1, message: '数据库错误' });
                  res.json({ code: 0, message: '结算成功', order_id: orderId });
                }
              );
            }
          );
        }
      );
    }
  );
});

// 支付订单（更新状态）
router.post('/pay', (req, res) => {
  const { order_id } = req.body;
  if (!order_id) {
    return res.status(400).json({ code: 1, message: '缺少订单ID' });
  }
  pool.query(
    'UPDATE `order` SET status = ? WHERE id = ?',
    ['已支付', order_id],
    (err, result) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, message: '支付成功' });
    }
  );
});

// 完成订单（管理员操作）
router.post('/complete', (req, res) => {
  const { order_id } = req.body;
  if (!order_id) {
    return res.status(400).json({ code: 1, message: '缺少订单ID' });
  }
  pool.query(
    'UPDATE `order` SET status = ?, complete_time = NOW() WHERE id = ?',
    ['已完成', order_id],
    (err, result) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, message: '订单已完成' });
    }
  );
});

// 删除订单（先删 order_goods，再删 order）
router.delete('/:id', (req, res) => {
  const id = req.params.id;
  // 先删除 order_goods
  pool.query('DELETE FROM order_goods WHERE order_id = ?', [id], (err) => {
    if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
    // 再删除 order
    pool.query('DELETE FROM `order` WHERE id = ?', [id], (err2) => {
      if (err2) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, message: '删除成功' });
    });
  });
});

// 获取订单详情（含商品明细）
router.get('/:id', (req, res) => {
  const order_id = req.params.id;
  pool.query(
    'SELECT og.quantity, g.name, g.price, g.image FROM order_goods og JOIN goods g ON og.goods_id = g.id WHERE og.order_id = ?',
    [order_id],
    (err, goods) => {
      if (err) return res.status(500).json({ code: 1, message: '数据库错误' });
      res.json({ code: 0, data: goods });
    }
  );
});

module.exports = router; 